<template>
  <div class="DialogBox">
    <div class="tree-box">
      <el-tree ref="tree" :data="TreeList" :props="defaultProps" :expand-on-click-node="false" default-expand-all>
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span style="margin-left: 10px;">
            <el-button v-if="data.pid == row.id" type="text" size="mini" @click="() => append(data)">添加二级字典</el-button>
            <el-button v-if="data.children.length <= 0" type="text" size="mini" @click="() => remove(node, data)">删除</el-button>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="buttom-box">
      <el-button @click="addDict()" type="danger">添加一级字典</el-button>
    </div>



    <!-- 目录新增弹框 -->
    <el-dialog title="添加字典" :visible.sync="dialog.visible" :close-on-click-modal="false" append-to-body width="20%">
      <el-input v-model="dialog.value" :placeholder="'请输入字典名称'" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="addDictOk">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    props: ["row"],
    data() {
      return {
        TreeList: [],

        dialog: {
          pid: null,
          value: '',
          visible: false
        },

        defaultProps: {
          children: 'children',
          label: 'name'
        },
      };
    },
    created: function() {
      // 获取联动树列表
      this.getDicTreeList();
    },
    methods: {
      // 获取联动树列表
      getDicTreeList: function() {
        let params = {
          pid: this.row.id,
        };
        this.$server.getDicTreeList(params).then(res => {
          this.TreeList = res.data;
        })
      },

      // 添加二级字典
      append: function(data) {
        this.dialog.pid = data.id;
        this.dialog.visible = true;
      },

      // 删除字典
      remove: function(node, data) {
        let params = {
          id: data.id,
        };
        this.$server.deleteDict(params).then(res => {
          this.getDicTreeList();
        });
      },

      // 添加一级字典
      addDict: function() {
        this.dialog.pid = this.row.id;
        this.dialog.visible = true;
      },

      // 确认添加字典
      addDictOk: function() {
        let dialog = this.dialog;
        if (dialog.value == '') {
          this.$message({
            showClose: true,
            message: '请输入名称',
            type: 'error'
          });
          return;
        }
        let params = {
          name: dialog.value,
          pid: dialog.pid,
        };
        this.$server.addDict(params).then(res => {
          this.dialog = {
            pid: null,
            value: '',
            visible: false,
          };
          this.getDicTreeList();
        });
      },
    }
  };
</script>
<style lang="scss" scoped>
  .DialogBox {
    .tree-box {
      margin-bottom: 50px;
    }
  }
</style>
